package com.mocoop.jfqc;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.cordova.CordovaWebViewImpl;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.mocoop.activity.MocoopActivity;
import com.mocoop.activity.MocoopTabHostSingletonActivity;
import com.mocoop.biz.CheckFirstRunBiz;
import com.mocoop.commom.MyConstants;
import com.mocoop.commom.MyOSS;
import com.mocoop.commom.MyTaskCallBack;
import com.mocoop.entity.AppBase;
import com.mocoop.entity.PageInfoEntity;
import com.mocoop.jfqc.JFQCActivity.BaseActivity;
import com.mocoop.plugin.user.APPInfo;
import com.mocoop.service.UpdateNotifyService;
import com.mocoop.task.AutoRequestTask;

public final class MainActivity extends MocoopTabHostSingletonActivity
		implements BaseActivity {

	private boolean firstShow = true;
	public JFQCActivity baseActivity;

	@Override
	public void onCreate(Bundle savedInstanceState) {
//		 CordovaWebViewImpl.setSystemWebView(true);
		MocoopActivity.setBASE_URL(MyConstants.BASE_URL);
		super.onCreate(savedInstanceState);

		baseActivity = new JFQCActivity(this);
		baseActivity.showLaunchView();
		MyOSS.Init(this, getUserID());
		baseActivity.registerMessageReceiver();

		String userID = getUserID();
		if ("".equals(userID)) {
			Intent intent = new Intent(this, LoginActivity.class);
			intent.putExtra(JFQCActivity.START_ACTIVITY_FOR_RESULT, true);
			startActivityForResult(intent, 1);
		} else {
			initUserData(userID);
		}
		checkUpdate(new UpdateInterface() {
					
			@Override
			public void updateCallBack(AppBase appInfo,int icon,String fileName) {
				doNewVersionUpdate(appInfo, icon,fileName);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if (requestCode == 1) {
			initUserData(getUserID());
		}
	}

	private void initUserData(String userID) {
		CheckFirstRunBiz firstRunBiz = new CheckFirstRunBiz(this, userID);
		firstRunBiz.setMyTaskCallBack(new MyTaskCallBack() {

			@Override
			public void onSuccess(Object obj) {
				changeCurrentWebView(baseActivity.getLaunchPage());
			}
		});
		firstRunBiz.checkDB();
	}

	@Override
	public void changeItemListener(int id) {

		changeCurrentWebView(baseActivity.changeItemListener(id));
	}

	
	
	@Override
	public void showMeRightNow() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (firstShow) {
					currentFragment.getCordovaWebView().loadUrl(
							"javascript:util.appInit();");
					firstShow = false;
				}
				currentFragment.hideTitleStatus();
				MainActivity.super.showMeRightNow();
			}
		});
	}

	@Override
	public void jumpNewPage(PageInfoEntity pageInfoEntity) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				currentFragment.showTitleStatus();
			}
		});
		super.jumpNewPage(pageInfoEntity);

	}

	@Override
	protected void onResume() {
		super.onResume();
		JPushInterface.onResume(this);

	};

	@Override
	protected void onPause() {
		super.onPause();
		JPushInterface.onPause(this);
	}

	@Override
	public void netListener(int netStatus) {
		super.netListener(netStatus);
		if (netStatus == WIFI_NET) {
			new AutoRequestTask(this).execute(new String[] { getUserID() });
		}
	}

	@Override
	public void messageCountController(String tabName, String msg) {
		baseActivity.messageCountController(tabName, msg);
	}

	@Override
	public JFQCActivity getJFQCActivity() {
		return baseActivity;
	}

	@Override
	protected void onStart() {
		super.onStart();
		baseActivity.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
		baseActivity.onStop();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		baseActivity.onDestroy();
	}
	
	
	public boolean getAppMode(){
		SharedPreferences sharedPreferences = getSharedPreferences("html"+getUserID(), 0);   

		String appMode = sharedPreferences.getString("appMode", "OFF");
		
		return "ON".equals(appMode);
	}
	
	@Override
	public boolean isNetworkConnected() {
		if(getAppMode()){
			return false;
		}
		return super.isNetworkConnected();
	}
	
	@Override
	public void ajaxRequest(int method, String url, JSONObject jsonObject,
			Listener<JSONObject> listener, ErrorListener errorlistener,
			int initialTimeoutMs) {
		
		
		
		if(getAppMode()){
			errorlistener.onErrorResponse(new VolleyError(""));
		}else{
		
		super.ajaxRequest(method, url, jsonObject, listener, errorlistener,
				initialTimeoutMs);
		
		}
		
	}

	public interface UpdateInterface{
		public void updateCallBack(AppBase appInfo,int icon,String fileName);
	}

	private String buildAppUUID() {
		return "S04" + UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	public void checkUpdate(final UpdateInterface updateInterface) {
		PackageInfo appInfo = null;
		try {
			appInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(appInfo == null){
			return;
		}
		JSONObject object = new JSONObject();
		try {
			object.put("projectKey", "QCAPP");
			object.put("type", "apk");
			object.put("appID", "0");
			object.put("version", appInfo.versionName);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		JSONArray requestArray = new JSONArray();
		requestArray.put(object);
		JSONObject request = new JSONObject();
		try {
			request.put("data", requestArray);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		String msgStr = "{\"Service\":" + "{\"Header\":" + "{\"Request\":" + "{ \"ServiceCode\":\"S10_VERSION_R_00002\", \"ReqSysCode\":\"S04\", \"SerialNumber\":\""
				+ buildAppUUID() + "\", \"ReqTime\":\"" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
				+ "\",\"ReqType\":\"0\",\"Bcode\":\"\", \"Security\":{ \"AppKey\":\"4c83c150-0852-11e5-be68-005056a68c0b\" } } }, \"Body\":{ \"Request\":" + request.toString()
				+ "} } }";
		JSONObject jsonObject = null;
		try {
			 jsonObject = new JSONObject(msgStr);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Method.POST, MyConstants.UPGRADE_SERVICE_URL, jsonObject, new Response.Listener<JSONObject>() {

			@Override
			public void onResponse(JSONObject response) {
				try {
					JSONArray jsonArray = response.getJSONObject("Service").getJSONObject("Body").getJSONArray("Response");
					Log.v(TAG, "Response="+jsonArray.toString());
					APPInfo appInfo = null;
					for (int i = 0; i < jsonArray.length(); i++) {
						if (jsonArray.getJSONObject(i).getInt("isLatest") == 0) {
							appInfo = new APPInfo();
							appInfo.setId(jsonArray.getJSONObject(i).getString("appID"));
							appInfo.setVersion(jsonArray.getJSONObject(i).getString("version"));
							appInfo.setUrl(jsonArray.getJSONObject(i).getString("url"));
							appInfo.setSize(jsonArray.getJSONObject(i).getLong("size"));
							appInfo.setForced(jsonArray.getJSONObject(i).getInt("forced"));
							appInfo.setDescription(jsonArray.getJSONObject(i).getString("description"));
						}
					}
					updateInterface.updateCallBack(appInfo,R.drawable.qc_icon,"JFGF");
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Log.v(TAG, "onErrorResponse..."+error.toString());
			}
		});
		Volley.newRequestQueue(this).add(jsonRequest);
	}
	
	public void doNewVersionUpdate(final AppBase mUpgradeInfo,final int icon,final String headName){
		 if(mUpgradeInfo == null)
			 return;
		PackageInfo appInfo = null;
		try {
			appInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(appInfo == null){
			return;
		}
	        StringBuffer sb = new StringBuffer();
	        sb.append("当前版本:");
	        sb.append(appInfo.versionName);
	        sb.append(" ,发现版本：");
	        sb.append(mUpgradeInfo.getVersion()+"\n");
	        sb.append("版本描述:"+mUpgradeInfo.getDescription());
	        sb.append(" ,是否更新?");
	        Dialog dialog = new AlertDialog.Builder(this)
	        .setTitle("版本更新")
	        .setMessage(sb.toString())
	        .setPositiveButton("更新", new DialogInterface.OnClickListener() {            
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	            	dialog.dismiss();
	            	Intent intent = new Intent(MainActivity.this,UpdateNotifyService.class);
	            	intent.putExtra("url", mUpgradeInfo.getUrl());
	            	String fileName = headName+"_v"+mUpgradeInfo.getVersion()+".apk";
	            	intent.putExtra("fileName", fileName);
	            	intent.putExtra("iconId", icon);
	            	startService(intent);
	            }
	        })
	        .setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
	            
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	            	dialog.dismiss();
	            }
	        }).create();
	        
	        dialog.setCanceledOnTouchOutside(false);
	        dialog.show();
	    }
}